package com.ksd.web.controller.tool;

import com.ksd.system.service.ISysOperLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

public class ContOsTool {

    private static final Logger logger = LoggerFactory.getLogger(ContOsTool.class);

    public static void setNetworkConfig(String ip, String netmask, String gateway,String mac, File file) {

        ///etc/sysconfig/network-scripts/ifconfg-th0xxxxx
//			File file = new File(UDRMConfig.getNetworkPath());
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;

            CharArrayWriter caw = new CharArrayWriter();
            while ((tempString = reader.readLine()) != null) {
                if (tempString.startsWith("IPADDR")) {
                    String replaceAll = tempString.replaceAll(tempString, "IPADDR=" + ip);
                    caw.write(replaceAll);
                    caw.append(System.getProperty("line.separator"));

                    logger.info("修改ip地址为: "+replaceAll);

                } else if (tempString.startsWith("NETMASK")) {
                    String replaceAll = tempString.replaceAll(tempString, "NETMASK=" + netmask);
                    caw.write(replaceAll);
                    caw.append(System.getProperty("line.separator"));
                    logger.info("修改子网掩码为: "+replaceAll);

                } else if (tempString.startsWith("GATEWAY")) {
                    String replaceAll = tempString.replaceAll(tempString, "GATEWAY=" + gateway);
                    caw.write(replaceAll);
                    caw.append(System.getProperty("line.separator"));
                    logger.info("修改网关为: "+replaceAll);

                } else if (tempString.startsWith("MAC")) {
                    String replaceAll = tempString.replaceAll(tempString, "MAC=" + gateway);
                    caw.write(replaceAll);
                    caw.append(System.getProperty("line.separator"));
                    logger.info("修改MAC地址为: "+replaceAll);

                } else {
                    caw.write(tempString);
                    caw.append(System.getProperty("line.separator"));
                }
            }
            reader.close();

            file.setWritable(true, true);
            FileWriter fw = new FileWriter(file);
            caw.writeTo(fw);
            fw.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    public static void restartNetworkService(HttpServletRequest request, ISysOperLogService sysOperLogService) {

        System.out.println("重启网络！！！！");
        sysOperLogService.insertOperlogSuccess("重启网络服务");
        logger.error("restart operation oh system ");
        String os = System.getProperty("os.name").toLowerCase();
        logger.error("\r\nOS info:" + os.toString());
        String cmd = "";
        Object exec = null;
        if (os.startsWith("win")) {
            /** **
             * windows 的还需要后期调试，执行CMD的时候回报错
             */
//			cmd = "shutdown.exe -r -t 1";
            cmd = "service network restart";
            exec = SystemTool.execResult("windows", cmd);

        } else {
//			cmd = "shutdown -r +1";
            cmd = "service network restart";
            exec = SystemTool.execResult("linux", cmd);

        }
        String string = exec.toString();
        logger.error(string);
        logger.error("客户端IP:" + request.getRemoteAddr() +"\t" + "username " +  request.getSession().getAttribute("userName") +" restart OS");
        sysOperLogService.insertOperlogSuccess("客户端IP:" + request.getRemoteAddr() +"\t" + "username " +  request.getSession().getAttribute("userName") +" restart OS");

    }

    public static void rebootService(){
        // 假设是使用netplan管理网络的系统，执行netplan apply命令
        String[] command = {"/bin/bash", "-c", "sudo netplan apply"};
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("网络服务重启成功");
            } else {
                System.out.println("网络服务重启失败，退出码: " + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

}
